package com.campus.happy;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class NetController implements OnItemClickListener, OnScrollListener {
	ListView listview;
	ArrayList<Info> list;
	ArrayList<Info> added;
	Request request;
	String url;
	Context context;
	InfoAdapter adapter;
	ProgressDialog dialog;

	public NetController(String string) {
		// TODO Auto-generated constructor stub
		this.url = string;

	}

	public void init(Context context) {
		this.context=context;
		listview = new ListView(context);
		list = new ArrayList<Info>();
		request = new Request(url);
		adapter = new InfoAdapter(context, list);
		listview.setAdapter(adapter);
		listview.setOnScrollListener(this);
		go();
		listview.setOnItemClickListener(this);
		dialog = new ProgressDialog(context);
		dialog.setTitle("网络加载中");
		dialog.show();
	}

	void update() {
		if (added == null) {
		} else {
			list.addAll(added);
			adapter.notifyDataSetChanged();

		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		switch (scrollState) {
		// 当不滚动时
		case OnScrollListener.SCROLL_STATE_IDLE:
			// 判断滚动到底部
			if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
				go();
			}
			break;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
	}

	View getView() {

		return listview;
	}

	void go() {
		new Thread() {
			public void run() {
				try {
					try {
						added = null;
						added = request.get();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Handler h = new Handler(Looper.getMainLooper());
					h.post(new Runnable() {

						@Override
						public void run() {

							// TODO Auto-generated method stub
							update();
							dialog.dismiss();
						}
					});
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}.start();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		InfoActivity.send((Activity)context,list.get(position).url,list.get(position).r);
	}
}
